//
//  ZBAvailability.m
//  ZBDay
//
//  Created by xzb on 2018/2/7.
//  Copyright © 2018年 xzb. All rights reserved.
//

#import "ZBAvailability.h"

extern int32_t __isOSVersionAtLeast(int32_t Major, int32_t Minor, int32_t Subminor);

@implementation ZBAvailability

+ (BOOL)isSystemVersionAvailable:(NSString *)pattern
{
    // pattern should be like: iOS 11.0
    static NSRegularExpression *regex;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        regex = [NSRegularExpression regularExpressionWithPattern:@"^(\\w+) (\\d+)(?:.(\\d+))?(?:.(\\d+))?$" options:0 error:nil];
    });
    
    NSTextCheckingResult *match = [regex firstMatchInString:pattern options:0 range:NSMakeRange(0, pattern.length)];
    if (match == nil) {
        Log(@"invalid @zb_available pattern %@ *, should be like @zb_available(iOS 9.0, *)", pattern);
        return NO;
    }
    
    NSRange majorRange = [match rangeAtIndex:2];
    NSRange minorRange = [match rangeAtIndex:3];
    NSRange subminorRange = [match rangeAtIndex:4];
    
#define EXTRACT(pattern, range) (((range.location != NSNotFound && range.length > 0 && range.location + range.length <= pattern.length) ? [pattern substringWithRange:range] : nil))
    
    int32_t major = (int32_t)[EXTRACT(pattern, majorRange) integerValue];
    int32_t minor = (int32_t)[EXTRACT(pattern, minorRange) integerValue];
    int32_t subminor = (int32_t)[EXTRACT(pattern, subminorRange) integerValue];
    
    return __isOSVersionAtLeast(major, minor, subminor);
}


@end
